package cn.tedu.mall.book.service.impl;

import cn.tedu.mall.book.ex.ServiceException;
import cn.tedu.mall.book.mapper.AdminMapper;
import cn.tedu.mall.book.pojo.dto.AdminLoginDTO;
import cn.tedu.mall.book.pojo.vo.AdminLoginVO;
import cn.tedu.mall.book.service.IAdminService;
import cn.tedu.mall.book.web.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author zxjun
 * @date 2022/6/7 21:00
 */
@Service
public class AdminServiceImpl  implements IAdminService {
    @Autowired
    AdminMapper adminMapper;

    @Override
    public String login(AdminLoginDTO adminLoginDTO, HttpSession session) {
        //根据用户名查看数据库中是否存在
        String username= adminLoginDTO.getUsername();
        AdminLoginVO adminLoginVO=adminMapper.getLoginInfoByUsername(username);
        //如果用户名不存在
        if (adminLoginVO==null){
            throw new ServiceException(State.ERR_NOT_FOUND,"管理员不存在");
        }
        //判断是否被禁用
        if (adminLoginVO.getIsEnable()!=1){
            throw new ServiceException(State.ERR_DELETE,"管理员被禁用");
        }

        //判断密码是否正确
        // 从参数中取出此次登录时客户端提交的密码
        String rawPassword=adminLoginDTO.getPassword();
        if (!adminLoginVO.getPassword().equals(rawPassword)){
            throw new ServiceException(State.ERR_NOT_FOUND,"管理员密码错误");
        }
        //密码正确，登录成功
        //把当前登录成功的用户对象保存到会话对象中
        session.setAttribute("admin",adminLoginVO);
        return "登录成功";
    }
}
